package com.dosimple.comparedatabase.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Map;

@Slf4j
public class PDFUtils {

    public static void write(byte[] contractByte, String outFile){
        FileChannel fc = null;
        try {
            ByteBuffer bb = ByteBuffer.wrap(contractByte);
            fc = new FileOutputStream(outFile).getChannel();
            fc.write(bb);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null!=fc){
                    fc.close();
                }
            } catch (IOException e) {
                log.error("关闭Stream 失败 ", e);
            }
        }

    }


    public static byte[] fillTemplate(Map<String, String> contract, File file){
        //读取pdf模板
        try {
            FileInputStream is = new FileInputStream(file);
            PdfReader reader = new PdfReader(is);
            return fillTemplate(contract, reader);
        } catch (IOException e) {
            log.error("读取PDF模板出错", e);
            throw new RuntimeException("读取PDF模板出错");
        }
    }


    public static byte[] fillTemplate(Map<String, String> contract, String url){

        InputStream is = PDFUtils.class.getResourceAsStream(url);

        //读取pdf模板
        try {
            PdfReader reader = new PdfReader(is);
            return fillTemplate(contract, reader);
        } catch (IOException e) {
            log.error("读取PDF模板出错", e);
            throw new RuntimeException("读取PDF模板出错");
        }

    }

    public static byte[] fillTemplate(Map<String, String> contract, byte[] bytes) {
        try {
            //读取pdf模板
            PdfReader reader = new PdfReader(bytes);
            return fillTemplate(contract, reader);
        } catch (IOException e) {
            log.error("生成合同出错", e);
            throw new RuntimeException("生成合同出错");
        }
    }

    private static byte[] fillTemplate(Map<String, String> contract, PdfReader reader){
        ByteArrayOutputStream bos = null;
        PdfStamper stamper;
        try {
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(baseFont);
            form.setSubstitutionFonts(fontList);


            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                System.out.println(name);
                System.out.println(contract.get(name));
                form.setField(name, contract.get(name));
            }
            //如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();

            byte[] content = bos.toByteArray();
            return content;

        } catch (IOException e) {
            log.error("生成合同出错", e);
            throw new RuntimeException("生成合同出错");
        } catch (DocumentException e) {
            log.error("生成合同出错", e);
            throw new RuntimeException("生成合同出错");
        } finally {
            try {
                if(null!=bos){
                    bos.close();
                }
                if(null!=reader){
                    reader.close();
                }
            } catch (IOException e) {
                log.error("关闭Stream 失败 ", e);
            }
        }
    }

    public static void htmlToPDF(String htmlString, String pdfPath) {
        try {
            InputStream htmlFileStream = new FileInputStream(htmlString);
            // 创建一个document对象实例
            Document document = new Document();
            // 为该Document创建一个Writer实例
            PdfWriter pdfwriter = PdfWriter.getInstance(document,
                    new FileOutputStream(pdfPath));
            pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
            // 打开当前的document
            document.open();
            InputStreamReader isr = new InputStreamReader(htmlFileStream, "UTF-8");
            XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document,htmlFileStream,null,null,new FontsProviderUtils());
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        PDFUtils.htmlToPDF("E:\\compare-database\\src\\main\\resources\\static\\index.html", "D:\\a.pdf");
    }
}
